package online.yysh.charging;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;

import online.yysh.charging.base.BaseActivity;
import online.yysh.charging.bean.request.BookingRequest;
import online.yysh.charging.bean.ChargingPile;
import online.yysh.charging.bean.response.GetDeatailPortInfoResponse;
import online.yysh.charging.bean.response.Station;
import online.yysh.charging.utils.HttpUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 预约充电
 */
public class SubscribeActivity extends BaseActivity {

    private TextView tv_cancel,tv_title;
    private Station chargingBean;
    private List<ChargingPile> chargingPiles = new ArrayList<>();
    private RecyclerView recyclerView;
    private MyAdapter adapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_subscribe;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            adapter.notifyDataSetChanged();
            if (chargingPiles.size() == 0){
                showToast("未查询到可预约电桩");
            }
        }
    };

    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_cancel = findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_title = findViewById(R.id.tv_title);
        tv_title.setText(R.string.pre_charge);
        recyclerView = findViewById(R.id.rv_subscribe);
        adapter = new MyAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void initData() {
        chargingBean = (Station) getIntent().getSerializableExtra("chargingBean");
        HttpUtil.getInstance().getDeatailPortInfo(chargingBean.getID() + "", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                showToast("未查询到可预约电桩");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                logD("result:" + result);
                if (result.contains("ok")){
                    GetDeatailPortInfoResponse resp = new Gson().fromJson(result, GetDeatailPortInfoResponse.class);
                    List<ChargingPile> chargingPileList = resp.getData();
                    chargingPiles = chargingPileList;
                    handler.sendEmptyMessage(200);
                }else{
                    showToast("未查询到可预约电桩");
                }
            }
        });
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.VH> {

        @NonNull
        @Override
        public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_subscribe, parent, false);
            return new MyAdapter.VH(view);
        }

        @Override
        public void onBindViewHolder(@NonNull VH holder, int position) {
            final ChargingPile chargingPile = chargingPiles.get(position);
            holder.tv_stationName.setText("电站名：" + chargingBean.getName());
            holder.tv_pileNumber.setText("桩号：" + chargingPile.getDeviceId());
            holder.tv_gunNumber.setText("枪号：" + chargingPile.getPort());
            holder.btn_subscribe.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showSubscribeDialog(chargingPile);
                }
            });
        }

        @Override
        public int getItemCount() {
            return chargingPiles.size();
        }

        class VH extends RecyclerView.ViewHolder {

            TextView tv_stationName, tv_pileNumber, tv_gunNumber;
            Button btn_subscribe;

            public VH(@NonNull View itemView) {
                super(itemView);
                tv_gunNumber = itemView.findViewById(R.id.tv_gun_number);
                tv_pileNumber = itemView.findViewById(R.id.tv_pile_number);
                tv_stationName = itemView.findViewById(R.id.tv_station_name);
                btn_subscribe = itemView.findViewById(R.id.btn_subscribe);
            }
        }
    }

    /**
     * 弹出预约对话框
     *
     * @param chargingPile
     */
    private void showSubscribeDialog(final ChargingPile chargingPile) {
        final AppCompatDialog appCompatDialog = new AppCompatDialog(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_subscribe, null);
        final TextView tv_info = view.findViewById(R.id.tv_info);
        tv_info.setText("桩号：" + chargingPile.getDeviceId() + "\r\n枪号：" + chargingPile.getPort());
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appCompatDialog.dismiss();
            }
        });
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                subscribe(chargingPile);
                appCompatDialog.dismiss();
            }
        });
        appCompatDialog.setContentView(view);
        Window window = appCompatDialog.getWindow();
        window.setBackgroundDrawableResource(R.color.transparent);
        window.setGravity(Gravity.CENTER);
        window.setLayout(800, ViewGroup.LayoutParams.WRAP_CONTENT);
        appCompatDialog.show();
    }

    /**
     * 预约充电
     *
     * @param chargingPile
     */
    public void subscribe(ChargingPile chargingPile) {
        String port = chargingPile.getPort();
        int portNumber = 0;
        if ("A".equals(port)) {
            portNumber = 65;
        } else if ("B".equals(port)) {
            portNumber = 66;
        }
        BookingRequest bookingRequest = new BookingRequest(openid, chargingPile.getDeviceId(), portNumber);
        HttpUtil.getInstance().booking(bookingRequest, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                showToast("预约失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                logE("result:" + result);
                if (result.contains("ok")){
                    showToast("预约成功");
                    finish();
                }else{
                    showToast("预约失败");
                }
            }
        });
    }
}